/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.flexengine.engine;

import com.flexengine.logger.Logger;
import com.flexengine.time.TimeManager;

/**
 * @author Luann R. Athayde
 * @version 1.0
 * @since 1.0
 */
public class FpsManager implements Runnable {

    private boolean run;
    private Thread  tFpsManager;

    private Integer ups;
    private Integer fps;
    private Integer skips;
    private Long    totalUps;
    private Long    totalFps;
    private Long    totalSkips;

    private FpsManager() {
        this.run = false;
        this.tFpsManager = null;
        this.ups = 0;
        this.fps = 0;
        this.skips = 0;
        this.totalUps = 0L;
        this.totalFps = 0L;
        this.totalSkips = 0L;
    }

    public void incrementFPS()  {
        fps++;
        totalFps++;
    }
    public void incrementUPS()  {
        ups++;
        totalUps++;
    }
    public void addSkips(Integer skips) {
        this.skips += skips;
        totalSkips += skips;
    }
    public void reset() {
        fps = 0;
        ups = 0;
        skips = 0;
    }

    public Integer getFps() {
        return fps;
    }
    public Integer getUps() {
        return ups;
    }
    public Integer getSkips() {
        return skips;
    }
    public Long getTotalFps() {
        return totalFps;
    }
    public Long getTotalUps() {
        return totalUps;
    }
    public Long getTotalSkips() {
        return totalSkips;
    }
    
    protected void debug(String root)    {
        String debug = root+": fps[" + fps + "] | ups[" + ups + "] | skips[" + skips + "]"
                + " | totalUps[" + totalUps + "] | totalFps[" + totalFps + "] | totalSkips[" + totalSkips + "]";
        Logger.logCore(debug);
    }
    protected void debugAndReset(String root) {
        debug(root);
        this.reset();
    }

    public void start() {
        reset();
        tFpsManager = new Thread(this, getClass().getSimpleName());
        tFpsManager.setDaemon(true);
        run = true;
        tFpsManager.start();
    }
    public void stop()  {
        run = false;
        tFpsManager = null;
        reset();
    }
    @Override
    public synchronized void run() {
        while(run) {
            try {
                this.wait(TimeManager.MILI_SECOND);
                this.debugAndReset(getClass().getSimpleName());
            } catch(InterruptedException e) {
                Logger.logWarning(getClass().getSimpleName()+": "+e.toString());
            }
        }
    }
    
    private static FpsManager instance;
    public static FpsManager getInstance() {
        if( instance == null ) {
            instance = new FpsManager();
        }
        return instance;
    }
    
}